package nf.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import nf.dao.UserDao;
import nf.dao.UserDaoImplJDBC;
import nf.entity.User;
import nf.service.UserService;
import nf.service.UserServiceImpl;
import nf.util.ConnUtil;


@WebServlet("/IndexAction")
public class IndexAction extends HttpServlet {
	
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8"); 
		
		UserService userService = new UserServiceImpl();
		
		int pageSize = 4;
		int pages;
		int mycount = 0;
		String currentPage_tmp = request.getParameter("currentPage"); 
		if (currentPage_tmp==null){
			currentPage_tmp = "1";
		}
		int currentPage = Integer.parseInt( currentPage_tmp );
		
		mycount = userService.getCount();
		List<User> userList = userService.getUserList( (currentPage-1)*pageSize+1, currentPage*pageSize);
		
		
		request.setAttribute("userList", userList);
		request.setAttribute("mycount", mycount);
		
		//request.getRequestDispatcher("index.jsp").forward(request, response);
		//跳转到jsp改为输出json（让所有的前端都可以引用）
		//System.out.println(userList);
		PrintWriter out = response.getWriter();
		ObjectMapper mapper = new ObjectMapper();
		String myJson = mapper.writeValueAsString(userList);
		out.print(myJson);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
